package com.ruoyi.project.module.products.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.UserUtils;
import com.ruoyi.common.utils.file.DownloadXls;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.service.DictService;
import com.ruoyi.project.common.domain.ErrorCommon;
import com.ruoyi.project.module.location.domain.Location;
import com.ruoyi.project.module.ordersHead.domain.OrdersHead;
import com.ruoyi.project.module.productsUpload.domain.ProductsUpload;
import com.ruoyi.project.system.dept.service.IDeptService;
import com.ruoyi.project.system.dict.domain.DictData;
import com.ruoyi.project.system.user.domain.User;
import org.apache.http.HttpRequest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.constant.BusinessType;
import com.ruoyi.project.module.products.domain.Products;
import com.ruoyi.project.module.products.service.IProductsService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.domain.AjaxResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 商品以及库存 信息操作处理
 *
 * @author lcx
 * @date 2018-08-15
 */
@Controller
@RequestMapping("/module/products")
public class    ProductsController extends BaseController {
    private String prefix = "module/products";
    private String prefix2 = "module/stockTaking";

    @Autowired
    private IProductsService productsService;
    @Autowired
    private DictService dict;
    @Autowired
    private IDeptService deptService;

    @RequiresPermissions("module:products:view")
    @GetMapping()
    public String products(ModelMap mmap) {
        mmap.put("depList", deptService.selectDeptAll());

        return prefix + "/products";
    }

    /**
     * @Author lcx
     * @Date 2018/9/20 18:16
     * 跳转到库存管理
     */
    @RequiresPermissions("module:stockTaking:view")
    @GetMapping("/stockTaking")
    public String stockTaking() {
        return prefix2 + "/stockTaking";
    }

    /**
     * 查询商品以及库存列表
     */
    @RequiresPermissions("module:products:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Products products,String selCompanyId) {
        startPageChange();
        products.setCompanyId(UserUtils.getDepId());
        //如果特殊处理的公司有筛选权限
        if (!(selCompanyId == null || "100".equals(selCompanyId))) {
            products.setCompanyId(selCompanyId);
        }
        List<Products> list = productsService.selectProductsList(products);

        /*查询合计*/
        List<Products> sumCountList = productsService.selectSumCountProductsList(products);

        return getDataTableAsSum(list,sumCountList);
    }

    /**
     * 查询库存盘点
     */
    @RequiresPermissions("module:stockTaking:list")
    @PostMapping("/stockTaking_list")
    @ResponseBody
    public TableDataInfo stockTaking_list(Products products) {
        startPageChange();
        products.setCompanyId(UserUtils.getDepId());
        List<Products> list = productsService.selectProductsList(products);

        /*查询合计*/
        List<Products> sumCountList = productsService.selectSumCountProductsList(products);

        return getDataTableAsSum(list,sumCountList);
    }

    /**
     * 跳转到新增商品
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
		/*List<DictData> dictData = dict.getType("erp_product_class");
		mmap.put("erp_product_class", dictData);*/

        return prefix + "/add";
    }

    @GetMapping("/history_list")
    public String historyList(ModelMap mmap) {
        return prefix + "/history_list";
    }

    /**
     * 新增保存商品信息
     */
    @RequiresPermissions("module:products:add")
    @Log(title = "商品以及库存", action = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Products products) {
        User user = ShiroUtils.getUser();
        products.setId(UUID.randomUUID().toString());
        products.setCreatorId(String.valueOf(user.getUserId()));
        products.setCompanyId(String.valueOf(user.getDeptId()));

        return toAjax(productsService.insertProducts(products));
    }

    /**
     * @Author lcx
     * @Date 2018/8/24 17:12
     * 保存批量上传的商品
     */
    @Log(title = "批量上传商品", action = BusinessType.INSERT)
    @PostMapping("/uploadProduct")
    @ResponseBody
    public AjaxResult uploadProduct(@RequestParam("list") String jsonList, String bz, ModelMap mmap) {

        List<ProductsUpload> phList = JSONObject.parseArray(jsonList, ProductsUpload.class);

        String download = RuoYiConfig.getProfile() + "productXls/";

        List<ErrorCommon> errorCommon = productsService.uploadProduct(phList,download,bz);

        if (errorCommon.size() > 0){
            return error(120,JSON.toJSON(errorCommon).toString());
        }

        return toAjax(2);
    }

    /**
     * 跳转到修改商品信息
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        Products products = productsService.selectProductsById(id);
        mmap.put("products", products);
        return prefix + "/edit";
    }

    /**
     * 跳转到修改库存信息
     */
    @GetMapping("/edit_inventory/{id}")
    public String editInventory(@PathVariable("id") String id, ModelMap mmap) {
        Products products = productsService.selectProductsById(id);
        mmap.put("products", products);
        return prefix + "/edit_inventory";
    }

    /**
     * @Author lcx
     * @Date 2018/9/21 11:46
     */
    @GetMapping("/edit_stockTaking/{id}")
    public String editStockTaking(@PathVariable("id") String id, ModelMap mmap) {
        Products products = productsService.selectProductsById(id);
        mmap.put("products", products);
        return prefix2 + "/edit_inventory";
    }

    /**
     * @Author lcx
     * @Date 2018/8/20 9:08
     */
    @GetMapping("/batch_add")
    public String batchadd(ModelMap mmap) {
        return prefix + "/batch_add";
    }

    /**
     * 修改保存商品信息
     */
    @RequiresPermissions("module:products:edit")
    @Log(title = "商品信息", action = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Products products) {
        return toAjax(productsService.updateProducts(products));
    }

    /**
     * 修改保存库存信息
     */
    @RequiresPermissions("module:products:edit_inventory")
    @Log(title = "库存信息", action = BusinessType.UPDATE)
    @PostMapping("/edit_inventory")
    @ResponseBody
    public AjaxResult editInventorySave(Products products) {
        return toAjax(productsService.updateProducts(products));
    }

    /**
     * 删除商品
     */
    @RequiresPermissions("module:products:remove")
    @Log(title = "商品以及库存", action = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(productsService.deleteProductsByIds(ids));
    }


    @Log(title = "商品图片上传", action = BusinessType.INSERT)
    @PostMapping("/FileUploadServlet")
    @ResponseBody
    public AjaxResult updateAvatar(User user, @RequestParam("avatarfile") MultipartFile file, HttpServletRequest request) {

        try {
            if (!file.isEmpty()) {
                String avatar = FileUploadUtils.upload(RuoYiConfig.getProfileProduct(), file);
                return success(avatar);
            }
            return error();
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @Log(title = "批量商品上传", action = BusinessType.IMPORT)
    @PostMapping("/FileUploadServletAsXls")
    @ResponseBody
    public AjaxResult updateExcle(User user, @RequestParam("exclefile") MultipartFile file, HttpServletRequest request) {

        try {
            String fileName = file.getOriginalFilename();
            String[] splitResult = fileName.split("\\.");
            String extension = "." + splitResult[splitResult.length - 1];
            if (!extension.equalsIgnoreCase(".xls") && !extension.equalsIgnoreCase(".xlsx")) {
                return error();
            }
            if (!file.isEmpty()) {
                String path = FileUploadUtils.upload(RuoYiConfig.getProfile() + "productXls/", file, extension);
                return fileUrl(fileName, path);
            }
            return error();
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @Log(title = "商品模板下载", action = BusinessType.IMPORT)
    @PostMapping("/exportDownLoadExcel")
    @ResponseBody
    public AjaxResult DownloadXlsAsProduct(HttpServletResponse response, String state) {

        String download = RuoYiConfig.getProfile() + "download";
        try {
            DownloadXls.downLoadFile(DownloadXls.DOWNLOADNAME_PRODUCT, DownloadXls.DOWNLOAD_TYPE_XLS, download, response);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }

    @Log(title = "弹出扫码盘点窗口", action = BusinessType.OTHER)
    @GetMapping("/toSweepCodeStockTaking")
    public String toSweepCodeStockTaking(ModelMap mmap,String flag){
        mmap.put("flag", flag);
        return prefix2 + "/sweepCodeStockTaking";
    }

    /**
     * @Author lcx
     * @Date /2018/10/12/ 11:04
     * 功能 stockIds 为特殊判断了的 此接口只支持 海外仓发货99数量一下的 扫码盘点 现需求不会很多 如果需要修改 请参考 purchases.print_label.html 下40行的方式 与本操作sql
     * */
    @Log(title = "扫码盘点", action = BusinessType.UPDATE)
    @PostMapping("/sweepCodeStockTaking")
    @ResponseBody
    public List<String> SweepCodeStockTaking(@RequestParam(value="stockIds[]") String[] stockIds) {

        return productsService.updateProductsAsSweepCodeStockTaking(stockIds);
    }


    /**
     * @Author lcx
     * @Date 2018/8/31 17:21
     * 校验主sku是否存在
     */
    @PostMapping("/checkMainSKU")
    @ResponseBody
    public String checkMainSKU(String mainSKU)
    {
        String uniqueFlag = "0";
        if (StringUtils.isNotNull(mainSKU))
        {
            uniqueFlag = productsService.selectProductsFlagByMainSKU(mainSKU);
        }
        return uniqueFlag;
    }

    /**
     * @Author lcx
     * @Date 2018/8/31 17:21
     * 校验主sku是否存在 存在返回商品信息
     */
    @PostMapping("/selectProductByMainSKU")
    @ResponseBody
    public Products selectProductByMainSKU(String mainSKU)
    {
        //todo  暂时没区分公司 暂且认为sku是唯一编码
        return productsService.selectProductsByMainSKU(mainSKU);
    }

    /*暂时使用*/
    @GetMapping("/print_test/{mainSKU}/{productName}/{size}")
    public String print_test(@PathVariable("mainSKU") String mainSKU,
                              @PathVariable("productName") String productName,
                                 @PathVariable("size") String size,
                              ModelMap mmap) {

        mmap.put("mainSKU", mainSKU);
        mmap.put("productName", productName);
        mmap.put("size", size);

        return prefix2 + "/print_label_test";
    }

}
